<template>
  <div>
    <div class="title">news.pool</div>
    <div class="text-black text-2xl font-bold flex">
      <el-row class="w-full">
        <el-col :span="18">
          <el-form :model="filterModel" label-align="left">
            <el-form-item label="新闻内容">
              <el-input v-model="filterModel.keywords" style="margin-left: 8px; width: 280px;"
                placeholder="请输入文章摘要或标题"></el-input>
            </el-form-item>

            <el-form-item label="新闻类型">
              <Catagory v-model="filterModel.classReal" title="新闻类型" :catlist="classCatsList"></Catagory>
            </el-form-item>

            <el-form-item label="筛选条件">
              <Filter v-model="filterModel.filter"></Filter>
            </el-form-item>

            <el-divider style="margin:4px 0"></el-divider>

            <el-button class="w-full" style="margin: 12px 0;color: rgba(0,0,0,0.65);border-style: dashed;"
              @click="handleCreate" @edit="handleEdit" v-permission="['write']">
              手动添加新闻
            </el-button>
          </el-form>
        </el-col>
      </el-row>
    </div>

    <div class="list-right-container">
      <div class="list-wrapper">
        <List :newsData="newsData" style="width: 100%; margin-left: 0px;" @add="handleAdd" @click="handleNewsClick"
          @remove="handleRemove" @refresh="fetchNewsData">
        </List>
      </div>

      <div class="rightbox">
        <div class="waitnews-container">
          <ReleaseList ref="releaseRef" />
        </div>
        <button class="releasebtn" @click="goToPublishSet" v-role="'admin'">发布设置</button>
      </div>
    </div>

    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.currentSize"
        :page-sizes="[10, 20, 50, 100]" :small="false" :disabled="false" :background="true"
        layout="total, sizes, prev, pager, next, jumper" :total="newsData.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <el-drawer v-model="drawer" title="I am the title" :with-header="false" size="50%" destroy-on-close>
      <Edit :mode="mode" :data="SelectNewsData" @close="drawer = false" @refresh="fetchNewsData" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch, useTemplateRef } from 'vue';
import { useRouter } from 'vue-router';
import List from './List.vue';
import Catagory from './Catagory.vue';
import Filter from './Filter.vue';
import { getNewsPool, updateNews, getNewsDetail } from '@/api/newspool';
import { ElMessage } from 'element-plus'
import ReleaseList from './ReleaseList.vue';
import Edit from './Edit.vue';

const router = useRouter();

const goToPublishSet = () => {
  router.push('/newspublish');
}
const classCatsList = [
  { value: -1, label: '全部' },
  { value: 1, label: '宏观环境' },
  { value: 2, label: '行业趋势' },
  { value: 3, label: '供应链动态' },
  { value: 4, label: '国际能源' },
  { value: 5, label: '其他' }
];
const releaseRef = useTemplateRef<{ releaseList: [], refresh: () => void }>('releaseRef');

const SelectNewsData = ref();
const drawer = ref(false);

const mode = ref<'read' | 'edit' | 'create'>('read')
const filterModel = reactive({
  keywords: '',
  classReal: -1,
  filter: {
    addMode: null,
    isPublished: null,
    timeRange: null,
    sortby: null,
  }
});

const handleAdd = async (id: number) => {
  try {
    if ((releaseRef.value?.releaseList as []).length >= 10) {
      ElMessage.warning('待发布新闻数量已达上限');
      return
    }
    const res = await updateNews({ id, isSelect: 1 });
    if (res.code === 200) {
      releaseRef.value?.refresh();
      const newRecords = newsData.value.records.map(item =>
        item.id === id ? { ...item, isSelect: 1 } : item
      );
      newsData.value = { ...newsData.value, records: newRecords };

      ElMessage.success('已加入待发布');
    }
  } catch (error) {
    console.error('加入失败:', error);
  }
};

const handleCreate = () => {
  drawer.value = true;
  mode.value = 'create';
}


const handleNewsClick = (newsData: any) => {
  drawer.value = true;
  mode.value = 'read';
  SelectNewsData.value = newsData;
}
const handleRemove = async (id: number) => {
  try {
    const res = await updateNews({ id, isSelect: 0 });
    if (res.code === 200) {
      const newRecords = newsData.value.records.map(item =>
        item.id === id ? { ...item, isSelect: 0 } : item
      );
      newsData.value = { ...newsData.value, records: newRecords };

      ElMessage.success('已移除待发布');
    }
  } catch (error) {
    console.error('移除失败:', error);
  }
};



const handleEdit = async (newsData: any) => {
  drawer.value = true;
  mode.value = 'edit';
  SelectNewsData.value = newsData;
}

watch(filterModel, (newVal) => {
  const { filter, ...rest } = newVal;
  const filterParams = { ...rest, ...filter };

  const finalParams = Object.entries(filterParams).reduce((prev, [key, value]) => {
    if (typeof value === 'string' && value || typeof value === 'number' && value >= 0 || Array.isArray(value)) {
      if (key === 'timeRange') {
        const [createTimeFrom, createTimeTo] = value as unknown as [string, string];
        return { ...prev, createTimeFrom, createTimeTo };
      }
      if (key === 'sortby' && value !== null) {
        return { ...prev, orderBy: value === 1 ? 'createTime asc' : 'createTime desc' };
      }
      return { ...prev, [key]: value };
    }
    return prev;
  }, {});

  pagination.value.current = 1;
  fetchNewsData(finalParams);

  const usp = new URLSearchParams(finalParams as unknown as Record<string, string>);
  console.log(usp.toString());
});

const newsData = ref<{ records: Record<string, unknown>[], total: number }>({ records: [], total: 0 });
const pagination = ref({ current: 1, currentSize: 10 });

const fetchNewsData = async (params = {}) => {
  try {
    const requestParams = {
      current: pagination.value.current,
      currentSize: pagination.value.currentSize,
      ...params
    };
    const response = await getNewsPool(requestParams);
    if (response && response.data) {
      newsData.value = response.data;
    }
  } catch (error) {
    console.error('获取新闻数据失败:', error);
    newsData.value = { records: [], total: 0 };
  }
};

const handleCurrentChange = (val: any) => {
  pagination.value.current = val;
  fetchNewsData();
};
const handleSizeChange = (val: any) => {
  pagination.value.currentSize = val;
  pagination.value.current = 1;
  fetchNewsData();
};

onMounted(() => {
  fetchNewsData();
});
</script>

<style scoped>
.title {
  font-size: 16px;
  font-weight: 500;
}

.text-2xl.font-bold {
  margin-bottom: 20px;
}

.list-right-container {
  position: relative;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto 30px;
  padding-right: calc(320px + 30px);
}

.list-wrapper {
  width: 680px;
  max-height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 10px;
  box-sizing: border-box;
  scrollbar-width: thin;
  scrollbar-color: #ddd #f5f5f5;
}

.list-wrapper::-webkit-scrollbar {
  width: 6px;
}

.list-wrapper::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}

.rightbox {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 30px;
  width: 320px;
  height: 700px;
  overflow-y: visible;
  overflow-x: hidden;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 16px;
  box-sizing: border-box;
  background: #fff;
}

.rightbox::-webkit-scrollbar {
  display: none;
}

.right-header {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.waitnews-container {
  min-height: calc(100% - 60px);
}

.releasebtn {
  width: 100%;
  height: 40px;
  margin-top: 16px;
  background: #409EFF;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.releasebtn:hover {
  background: #337ab7;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  clear: both;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 16px;
}
</style>